import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { AppServiceUtility } from "src/projects/app/appService";
import './index.less';
import { Input, Form, Radio, Select, DatePicker, Button } from "antd";
import { Card, Toast } from "antd-mobile";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import moment from "moment";

/**
 * 组件：长者护理模板页控件状态
 */
export interface elderlyCareTemplateViewState extends ReactViewState {
    /** 长者信息对象 */
    elderinfo?: object;
    /** 护理模板数据 */
    templatedata?: any;
    /** 用户选中的模板值 */
    templateid?: any;
    /** 用户选中的模板数据 */
    data?: any;
    /** 时间空间显示状态 */
    mode: string;
    /*申请表里的选项和值 */
    project?: any;
    /** data */
    useractive?: any;
    datavalue?: Date;
}

export interface addNursingRecordListFormValues {
    id?: string;
}

/** 时间合集 */
let timedata: string[] = [];

/**
 * 组件：长者护理模板页控件
 */
export class elderlyCareTemplateView extends ReactView<elderlyCareTemplateViewControl, elderlyCareTemplateViewState> {
    public lv: any = null;
    constructor(props: any) {
        super(props);
        this.state = {
            elderinfo: {},
            templatedata: [],
            templateid: [],
            project: [],
            mode: "time",
            data: [],
            useractive: [],
            datavalue: new Date()
        };
    }
    componentDidMount() {
        AppServiceUtility.assessment_template_service.get_assessment_template_list_all!({}, 1, 10)!
            .then((data: any) => {
                let templatedata: any = [];
                let items: any = [];
                data.result.forEach((item: any) => {
                    templatedata.push({
                        label: item.template_name,
                        value: item.id
                    });
                    items.push('');
                });
                this.setState({
                    templatedata,
                    useractive: items
                });
            });
        AppServiceUtility.person_org_manage_service.get_personnel_elder!({ id: this.props.match!.params.key }, 1, 10)!
            .then((data: any) => {
                this.setState({
                    elderinfo: data.result[0]
                });
            });
    }
    componentDidUpdate() {

    }
    handleok(e: any) {
        let data = [];
        data.push(e);
        this.setState({ templateid: data }, () => {
            AppServiceUtility.assessment_template_service.get_assessment_template_list_all!({ id: e })!
                .then((data: any) => {
                    this.setState({
                        data: data.result
                    });
                });
        });
    }
    handlePanelChange = (value: any, mode: any) => {
        this.setState({ mode });
    }
    Change = (date: any, dateString: string, index: number) => {
        if (dateString) {
            timedata[index] = dateString;
        }
    }
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: addNursingRecordListFormValues) => {
            console.log('asdsads>>>', values);
            let obj: any = {}, project_list = [] as any[];
            let list = [];
            // Object.keys(values).map(key => {
            //     console.log('key>>', key);
            //     console.log('obj>>>', obj[key]);
            // });
            let index = -1;
            for (let key in values) {
                if (key.indexOf('___') > 0) {
                    index++;
                    if (key.split('___').length > 2) {
                        list = key.split('___');
                        let radio_list = [];
                        radio_list = list[1].split(';');
                        let new_radio_list: any = [];
                        radio_list.forEach((item: any) => {
                            new_radio_list.push(JSON.parse(item));
                        });
                        let project = {
                            ass_info: {
                                project_name: list[0],
                                dataSource: new_radio_list,
                                selete_type: list[2],
                                value: values[key]
                            },
                            timedata: timedata[index]
                        };
                        project_list.push(project);
                    } else {
                        let project = {
                            ass_info: {
                                project_name: key.split('___')[0],
                                selete_type: key.split('___')[1],
                                value: values[key]
                            },
                            timedata: timedata[index]
                        };
                        project_list.push(project);
                    }

                } else {
                    obj[key] = values[key];
                }
                // });
            }
            obj['project_list'] = project_list;
            obj['elder'] = this.props.match!.params.key;
            obj['template'] = this.state.templateid[0];
            // 把对象组装调用接口，按照每个题目生成一条数据
            AppServiceUtility.nursing_record.update_nursing_recode!({ obj })!
                .then((data: any) => {
                    if (data === 'Success') {
                        Toast.info('操作成功！', 2);
                        this.props.history!.push(ROUTE_PATH.home);
                    }
                });
        });
    }
    render() {
        function idcard(idCard: string) {
            if (idCard) {
                let uw = idCard.replace(/(\w)/g, function (a, b, c, d) {
                    return ((c > 1 && c < 6) || c > (idCard.length - 5)) ? '*' : a;
                });
                return uw;
            } else {
                return idCard;
            }
        }
        const { getFieldDecorator } = this.props.form!;
        let project: any;
        let date = new Date();
        /** 用户选择的数组 */
        if (this.state.data) {
            project = [];
            this.state.data!.forEach((item: any, index: number) => {
                if (item.hasOwnProperty("ass_info")) {
                    if (item.ass_info.hasOwnProperty("selete_type")) {
                        if (item.ass_info.selete_type === "1") {
                            let radio_list = '';
                            let item_content: any;
                            if (item.ass_info.hasOwnProperty("dataSource")) {
                                item.ass_info.dataSource.forEach((item: any) => {
                                    radio_list = radio_list + JSON.stringify(item) + ";";
                                });
                                radio_list = radio_list.slice(0, radio_list.length - 1);
                                console.log(radio_list, "a-----------------------------------");
                                item_content = (
                                    <Form.Item label={item.ass_info.project_name}>
                                        {getFieldDecorator(item.ass_info.project_name + "___" + radio_list + "___1", {
                                            initialValue: item.ass_info.value ? item.ass_info.value : '',
                                            rules: [{
                                                required: true,
                                                message: '请选择' + item.ass_info.project_name,
                                            }],
                                        })(
                                            <div>
                                                <Radio.Group>
                                                    {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                        return <Radio value={i.serial_number} key={idx}>{i.option_content}</Radio>;
                                                    })}
                                                </Radio.Group>
                                                <DatePicker
                                                    defaultValue={moment(date)}
                                                    mode={(this.state.mode as any)}
                                                    showTime={true}
                                                    onPanelChange={this.handlePanelChange}
                                                    onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                                />
                                            </div>
                                        )}
                                    </Form.Item>
                                );
                            }
                            project.push(item_content);
                            return project;
                        }
                        if (item.ass_info.selete_type === "4") {
                            let radio_list = '';
                            let item_content: any;
                            if (item.ass_info.hasOwnProperty("dataSource")) {
                                item.ass_info.dataSource.forEach((item: any) => {
                                    radio_list = radio_list + JSON.stringify(item) + ";";
                                });
                                radio_list = radio_list.slice(0, radio_list.length - 1);
                                item_content = (
                                    <Form.Item label={item.ass_info.project_name}>
                                        {getFieldDecorator(item.ass_info.project_name + '___' + radio_list + '___4', {
                                            initialValue: item.ass_info.value ? item.ass_info.value : '',
                                            rules: [{
                                                required: true,
                                                message: '请选择' + item.ass_info.project_name,
                                            }],
                                        })(
                                            <div>
                                                <Select defaultValue={item.ass_info.dataSource[0].name} style={{ width: 120 }}>
                                                    {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                        return <option key={idx} value={i.serial_number}>{i.option_content}</option>;
                                                    })}
                                                </Select>
                                                <DatePicker
                                                    mode={(this.state.mode as any)}
                                                    showTime={true}
                                                    onPanelChange={this.handlePanelChange}
                                                    onChange={(e: any, datastring: any) => { this.Change(e, datastring, index); }}
                                                />
                                            </div>
                                        )}
                                    </Form.Item>
                                );
                            }
                            project.push(item_content);
                            return project;
                        }
                        if (item.ass_info.selete_type === "3") {
                            const item_content = (
                                <Form.Item label={item.ass_info.project_name}>
                                    {getFieldDecorator(item.ass_info.project_name + '___3', {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <div>
                                            <Input value={this.state.project} />
                                            <DatePicker
                                                mode={(this.state.mode as any)}
                                                showTime={true}
                                                onPanelChange={this.handlePanelChange}
                                                onChange={(e: any, datastring: any) => { this.Change(e, datastring, index); }}
                                            />
                                        </div>
                                    )}
                                </Form.Item>
                            );
                            project.push(item_content);
                            return project;
                        }
                    }
                } else {
                    return true;
                }
            });
        }
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 2 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 22 },
            },
        };
        return (
            <div className="elderly-care-template">
                <div style={{ padding: '0 15px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', lineHeight: '50px', color: '#888', fontSize: 18, borderBottom: '1px solid #F6F6F6' }}><span>{this.state.elderinfo!['name']}</span><span>{this.state.elderinfo!['nation']}</span></div>
                    <div style={{ display: 'flex', padding: '15px 0' }}>
                        <div style={{ fontWeight: 'bold', flex: '0 1 50%', maxWidth: '50%' }}>{this.state.elderinfo!['sex']}</div>
                        <div style={{ flex: '0 1 50%', maxWidth: '50%' }}>{idcard(this.state.elderinfo!['id_card'])}</div>
                    </div>
                    <div style={{ textAlign: 'right', paddingBottom: '8px', display: 'flex' }}>
                        <div style={{ flex: '0 1 50%', maxWidth: '50%' }}>{this.state.elderinfo!['native_place']}</div>
                        <div style={{ flex: '0 1 50%', maxWidth: '50%' }}>{this.state.elderinfo!['telephone']}</div>
                    </div>
                </div>
                <Select onChange={(e) => this.handleok(e)} style={{ width: 120, display: 'block', margin: 'auto auto 10px auto' }}>
                    {
                        this.state.templatedata && this.state.templatedata.length > 0 ?
                            this.state.templatedata.map((item: any, index: number) => {
                                return (<option value={item.value} key={index}>{item.label}</option>);
                            }) : null
                    }
                </Select>
                {project ? <Card>
                    <Card.Header
                        title="护理内容"
                        extra={<span>请选择对应的护理状态</span>}
                    />
                    <Card.Body >
                        <Form {...formItemLayout} onSubmit={this.handleSubmit} className="template-form">
                            {project}
                            <Button htmlType='submit' type='primary'>保存</Button>
                        </Form>
                    </Card.Body>
                </Card> : null}
            </div>
        );
    }
}

/**
 * 组件： 长者护理模板页控件
 * 控制长者护理模板页控件
 */
@addon('elderlyCareTemplateView', '长者护理模板页控件', '控制长者护理模板页控件')
@reactControl(Form.create<any>()(elderlyCareTemplateView), true)
export class elderlyCareTemplateViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}
